﻿using AutoMapper;
using D.Util.UtilIoc;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace D.Util.UtilAutoMapper
{
    /// <summary>
    /// 实体互转映射
    /// AutoMapper
    /// Microsoft.Extensions.DependencyInjection.Abstractions
    /// </summary>
    public static class AutoMapperUtil
    {
        /// <summary>
        /// 添加AutoMapper
        /// </summary>
        /// <param name="services">注入到服务</param>
        /// <param name="dtoToEntity">视图类转实体类</param>
        /// <param name="entityToDto">实体类转视图类</param>
        public static void AddAutoMapperStartup(this IServiceCollection services, Dictionary<Type, Type> dtoToEntity, Dictionary<Type, Type> entityToDto = null)
        {
            // 反射所有AutoMapper集成Profile的类
            var assemblies = RuntimeHelper.GetAllAssemblies().ToList();

            var mapperConfig = new MapperConfiguration(cfg =>
            {
                // 添加自定义的映射配置
                if (dtoToEntity.Count > 0 || entityToDto.Count > 0)
                {
                    cfg.AddProfile(new MappingProfile(dtoToEntity, entityToDto));
                }

                assemblies.ForEach(assembly =>
                {
                    var serviceTypes = assembly.GetTypes()
                                               .Where(t => t.IsClass && t.Name.EndsWith("Profile") && t.BaseType == typeof(Profile) &&
                                                               t.CustomAttributes.Any(attr => attr.AttributeType == typeof(AutoMapperProfileAttribute)))
                                               .ToList();

                    // 全部自动化添加
                    foreach (var type in serviceTypes)
                    {
                        UtilConsole.ConsoleUtil.Waring($"添加AutoMapper映射类：{type.FullName}");
                        cfg.AddProfile(type);
                    }
                });
            });
            IMapper mapper = mapperConfig.CreateMapper();
            services.AddSingleton(mapper);
        }
    }
}
